
<template>
  <!-- 经费账账簿查询 页面-->
  <div style="display:flex;flex-direction: column;height:100%">
    <div id="selectOne">
      <cus-allcard style="padding-bottom:0;"
                   :showTitle="false">
        <div class="topBody">
          <div class="topBodyItem">
            <span class="itemSpan">账簿年度</span>
            <Select v-model="selectForm.accountbookId"
                    placeholder="请选择账簿年度"
                    @on-change="accountbookIdChange()"
                    class="itemImport">
              <Option v-for="item in selectForm.yearList"
                      :value="item.accountbookId"
                      :key="item.year">{{ item.year }}</Option>
            </Select>
          </div>
          <div class="topBodyItem">
            <!-- <span class="itemSpan">查询日期：</span>
            <Date-picker type="month"
                         v-model="selectForm.selectMonth"
                         :clearable="false"
                         :options="timeOptions"
                         placeholder="请选择截止日期"
                         @on-change="getStartAndEnd($event)"
                         class="itemImport"></Date-picker> -->
            <span class="itemSpan">起始日期</span>
            <Date-picker type="date"
                         v-model="selectForm.starttime"
                         :clearable="false"
                         :options="timeOptions"
                         placeholder="请选择起始日期"
                         @on-change="tiemStartChange()"
                         class="itemImport"></Date-picker>
          </div>
          <div class="topBodyItem">
            <span class="itemSpan">截止日期</span>
            <Date-picker type="date"
                         v-model="selectForm.endtime"
                         :clearable="false"
                         :options="timeOptions"
                         placeholder="请选择截止日期"
                         @on-change="tiemEndChange()"
                         class="itemImport"></Date-picker>
          </div>
          <div class="topBodyItem">
            <cus-Button type="primary"
                        @onClick="getAllSubjectTotalApi"
                        class="ml_10"
                        v-permission="20">查询</cus-Button>
          </div>
        </div>
      </cus-allcard>
    </div>
    <div style="flex:1;"
         class="tableBox">
      <cus-allcard style="margin-top:24px;padding-top:24px"
                   :showTitle="false">
        <cusTable border
               :loading="form.loading"
               :columns="columns"
               :data="data"
               :bottomClass="[ 'cus-page' ]"
               :size="vuex_config.tableSize">
          <!-- isTotalFlag==3，没有值时，显示查看详情以及凭证编号 -->

          <template slot-scope="{ row }"
                    slot="snzrrecMoney">
            {{totalPrices(row.snzrrecMoney)}}
          </template>
          <template slot-scope="{ row }"
                    slot="snzrpayMoney">
            {{totalPrices(row.snzrpayMoney)}}
          </template>

          <template slot-scope="{ row }"
                    slot="byhjrecMoney">
            {{totalPrices(row.byhjrecMoney)}}
          </template>
          <template slot-scope="{ row }"
                    slot="byhjpayMoney">
            {{totalPrices(row.byhjpayMoney)}}
          </template>

          <template slot-scope="{ row }"
                    slot="ncljrecMoney">
            {{totalPrices(row.ncljrecMoney)}}
          </template>
          <template slot-scope="{ row }"
                    slot="ncljpayMoney">
            {{totalPrices(row.ncljpayMoney)}}
          </template>

          <template slot-scope="{ row }"
                    slot="direction">
            <span v-if="row.remainMoney>0">收</span>
            <span v-if="row.remainMoney==0">平</span>
            <span v-if="row.remainMoney<0">付</span>
          </template>
          <template slot-scope="{ row }"
                    slot="remainMoney">
            <span v-if="row.remainMoney<0"> {{totalPrices(-row.remainMoney)}}</span>
            <span v-if="row.remainMoney>=0"> {{totalPrices(row.remainMoney)}}</span>
          </template>

        </cusTable>
        <div style="width: 100%; display: flex; justify-content: flex-end">
          <cus-page :data="pages"
                    class="mt_10"
                    @pageChange="getAllSubjectTotalApi()"></cus-page>
        </div>
      </cus-allcard>
    </div>
  </div>
</template>
<script>
import {
  getAccountBookByUserId,
  getAllSubjectTotal
} from '@/api/businessAccountingApi/essentialInformationApi'
export default {
  data () {
    return {
      superiorState: false,
      form: {
        loading: false,
        name: '',
        startTime: '',
        endTime: ''
      },
      // 查询条件的集合
      selectForm: {
        year: null, // 账薄年度
        isjiezhuan: null, // 是否结转
        yearList: [], // 账薄年度列表
        accountbookId: null, // 账簿id
        starttime: null, // 起始日期
        endtime: null,// 截至日期
        selectMonth: null,// 查询日期
      },
      // 表头
      columns: [
        {
          title: '序号',
          type: 'index',
          align: 'center',
          minWidth: 70
        },
        {
          title: '科目编码',
          key: 'subjectcode',
          align: 'center',
          minWidth: 100
        },
        {
          title: '科目名称',
          key: 'subjectname',
          align: 'center',
          minWidth: 100
        },
        // {
        //   title: '科目名称',
        //   key: 'subjectfullname',
        //   align: 'center',
        //   minWidth: 100
        // },
        {
          title: '上年转入（期初余额）',
          align: 'center',
          children: [{
            title: '收方',
            slot: 'snzrrecMoney',
            align: 'right',
            minWidth: 100
          },
          {
            title: '付方',
            slot: 'snzrpayMoney',
            align: 'right',
            minWidth: 100
          }
          ]
        },
        {
          title: '本月合计',
          align: 'center',
          children: [{
            title: '收方',
            slot: 'byhjrecMoney',
            align: 'right',
            minWidth: 100
          },
          {
            title: '付方',
            slot: 'byhjpayMoney',
            align: 'right',
            minWidth: 100
          }
          ]
        },
        {
          title: '年初以来累计',
          align: 'center',
          children: [{
            title: '收方',
            slot: 'ncljrecMoney',
            align: 'right',
            minWidth: 100
          },
          {
            title: '付方',
            slot: 'ncljpayMoney',
            align: 'right',
            minWidth: 100
          }
          ]
        },
        {
          title: '余额',
          align: 'center',
          children: [{
            title: '收或付',
            slot: 'direction',
            align: 'center',
            minWidth: 100
          },
          {
            title: '余额',
            slot: 'remainMoney',
            align: 'right',
            minWidth: 100
          }
          ]
        },


      ],
      data: [], // 表格列表
      // 分页
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0
      },
      timeOptions: {
        disabledDate (date) {
          return (
            date < new Date(new Date().Format('yyyy') - 1 + '-12-31') || date > new Date(new Date().Format('yyyy-MM-dd'))
          )
        }
      },
    

    }
  },
  activated () {
    if (this.$route.query.superior == 'home') {
      this.superiorState = true
    } else {
      this.superiorState = false
    }
  },
  mounted () {

   
    this.getAccountBookByUserIdApi()// 根据用户id查询账簿 接口
  },

  methods: {
    // 千位分割符
    totalPrices (recmoney) {
      const intPart = Math.trunc(recmoney)//整数部分
      let floatPart = 0
      const intPartFormat = intPart.toString().replace(/\B(?=(\d{3})+$)/g, ',')
      const valuArray = Number(recmoney).toString().split('.')

      if (valuArray.length === 2) {//有小数部分
        if (valuArray[1]) {
          if (valuArray[1].length === 1) {
            valuArray[1] += '0'
          }
        } else {
          valuArray[1] = '00'
        }
        floatPart = valuArray[1]//取得小数部分

        return intPartFormat + '.' + floatPart
      } else {
        return intPartFormat + '.00'
      }
    },


    // 根据用户id查询账簿 接口
    getAccountBookByUserIdApi () {
      this.form.loading = true
      return new Promise((resolve) => {
        getAccountBookByUserId({
          userid: this.vuex_user.base.id // 用户id
        }).then((res) => {
          this.form.loading = false
          if (res.errorcode === 0) {
            this.selectForm.yearList = res.basAccountbookList
            this.selectForm.accountbookId = res.basAccountbookList[0].accountbookId
            this.selectForm.year = res.basAccountbookList[0].year // 账簿年度
            this.selectForm.isjiezhuan = res.basAccountbookList[0].isjiezhuan
            if (this.selectForm.year == new Date().Format('yyyy')) { //本年度时 - 用1月1日至当前时间
              this.selectForm.selectMonth = new Date()
              this.getStartAndEnd(new Date())
            } else { //非本年度时 - 用1月1日至12月31日
              // this.selectForm.selectMonth = this.selectForm.year + '-01-01'
              // this.getStartAndEnd(this.selectForm.year + '-01-01')
              this.selectForm.selectMonth = `${this.selectForm.year}-12-${new Date(this.selectForm.year, 12, 0).getDate()}`
              this.getStartAndEnd(`${this.selectForm.year}-12-${new Date(this.selectForm.year, 12, 0).getDate()}`)
            }
            this.optionDate() // 限制日期封装方法
            this.getAllSubjectTotalApi()// 账簿查询-科目余额表查询 接口
            resolve()
          } else {
            this.$Message.error(res.resultmsg)
          }
        })
      })
    },

    // 账簿查询-科目余额表查询 接口
    getAllSubjectTotalApi () {
      this.form.loading = true
      return new Promise((resolve) => {
        getAllSubjectTotal({
          accountbookId: this.selectForm.accountbookId,// 账簿ID	
          beginTime: new Date(this.selectForm.starttime).Format('yyyy-MM-dd'),// 查询开始时间	
          endTime: new Date(this.selectForm.endtime).Format('yyyy-MM-dd'),// 查询结束时间	
          current: this.pages.page,// 页数	
          size: this.pages.pageSize// 每页条数
        }).then((res) => {
          this.form.loading = false
          if (res.retCode === 0) {
            this.data = res.data
            this.pages.pageTotal = res.total
            resolve()
          } else {
            this.$Message.error(res.retMsg)
          }
        })
      })
    },

    // 账簿年度改变回调
    accountbookIdChange () {
      this.pages.page = 1
      this.selectForm.yearList.forEach(element => {
        if (element.accountbookId === this.selectForm.accountbookId) {
          this.selectForm.year = element.year
          this.selectForm.isjiezhuan = element.isjiezhuan
          if (this.selectForm.year == new Date().Format('yyyy')) { //本年度时 - 用1月1日至当前时间
            this.selectForm.selectMonth = new Date()
            this.getStartAndEnd(new Date())
          } else { //非本年度时 - 用1月1日至12月31日
            // this.selectForm.selectMonth = this.selectForm.year + '-01-01'
            // this.getStartAndEnd(this.selectForm.year + '-01-01')
            this.selectForm.selectMonth = `${this.selectForm.year}-12-${new Date(this.selectForm.year, 12, 0).getDate()}`
            this.getStartAndEnd(`${this.selectForm.year}-12-${new Date(this.selectForm.year, 12, 0).getDate()}`)
          }
          this.optionDate() // 限制日期封装方法
        }
      })
    },

    // 限制日期封装方法
    optionDate () {
      if (this.selectForm.year == new Date().Format('yyyy')) { // 本年度 - 限制：1月~当前月（不能跨年）
        this.timeOptions = {
          disabledDate (value) {
            return (
              value < new Date(new Date().Format('yyyy') - 1 + '-12-31') || value > new Date(new Date().Format('yyyy-MM-dd'))
            )
          }
        }
      } else {// 非本年度 - 限制：1月~12月（不能跨年）
        let startOption = (Number(this.selectForm.year) - 1) + '-12-31' // 限制开始能点日期 必须先建变量存储，才能放进new Date()
        let endOption = (Number(this.selectForm.year)) + '-12-31' // 限制结束能点日期 必须先建变量存储，才能放进new Date()
        this.timeOptions = {
          disabledDate (value) {
            return value < new Date(startOption) || value > new Date(endOption)
          }
        }
      }
    },

    // 起始日期改变回调
    tiemStartChange () {
      this.selectForm.starttime = new Date(this.selectForm.starttime).Format('yyyy-MM-dd')
      this.selectForm.endtime = new Date(this.selectForm.endtime).Format('yyyy-MM-dd')
      if (new Date(this.selectForm.starttime).Format('MM') > new Date(this.selectForm.endtime).Format('MM')) { //起始日期月份 大于 截止日期月份
        this.$Message.info("起始日期大于截止日期")
        this.selectForm.endtime = ''
      } else if (new Date(this.selectForm.starttime).Format('MM') == new Date(this.selectForm.endtime).Format('MM')) { //起始日期月份 等于 截止日期月份
        if (new Date(this.selectForm.starttime).Format('dd') > new Date(this.selectForm.endtime).Format('dd')) {
          this.$Message.info("起始日期大于截止日期")
          this.selectForm.endtime = ''
        }
      }
    },
    // 截止日期改变回调
    tiemEndChange () {
      this.selectForm.starttime = new Date(this.selectForm.starttime).Format('yyyy-MM-dd')
      this.selectForm.endtime = new Date(this.selectForm.endtime).Format('yyyy-MM-dd')
      if (new Date(this.selectForm.starttime).Format('MM') > new Date(this.selectForm.endtime).Format('MM')) { //起始日期月份 大于 截止日期月份
        this.$Message.success("截止日期大于起始日期")
        this.selectForm.starttime = ''
      } else if (new Date(this.selectForm.starttime).Format('MM') == new Date(this.selectForm.endtime).Format('MM')) { //起始日期月份 等于 截止日期月份
        if (new Date(this.selectForm.starttime).Format('dd') > new Date(this.selectForm.endtime).Format('dd')) {
          this.$Message.success("截止日期大于起始日期")
          this.selectForm.starttime = ''
        }
      }
    },

    // 查询日期改变回调-每次变更，获取当前月头与月末
    getStartAndEnd (valueData) {
      let dataYear = new Date(valueData).Format('yyyy') //获取年份
      let dateMonth = new Date(valueData).Format('MM') //获取月份
      let dateDay = new Date(valueData).Format('dd') //获取日

      let dataObj = new Date(dataYear, dateMonth, 0)  //获取当前月份最后一日
      let EndDateDay = dataObj.getDate() 

      this.selectForm.starttime = dataYear + '-01-01' //月头 返回整体日期 '2022-01-01'
      this.selectForm.endtime = dataYear + '-' + dateMonth + '-' + dateDay //月末 返回整体日期 '2022-05-31'
      this.getAllSubjectTotalApi() // 账簿查询-科目余额表查询 接口
    },
  }
}
</script>
<style lang="less" scoped>
.topBody {
  display: flex;
  padding-top: 24px;
  align-items: center;
  flex-wrap: wrap;
  .topBodyItem {
    display: flex;
    align-items: center;
    margin-right: 12px;
    margin-bottom: 20px;
    .itemSpan {
      white-space: nowrap;
      width: 80px;
      text-align: right;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.85) !important;
      margin-right: 10px;
    }
    .itemImport {
      width: 200px;
    }
  }
}
</style>
